package ai.assist.common.utils;

import ai.assist.common.exception.BusinessException;

/**
 * @author hui
 * @Date 2024/7/2 17:46
 **/
public class CoordinateConverter {

    private static final double PI = 3.1415926535897932384626;
    private static final double A = 6378245.0;
    private static final double EE = 0.00669342162296594323;

    /**
     * 将高德地图的经纬度转换成天地图的经纬度
     * @return 天地图经纬度数组，[0]为经度，[1]为纬度
     */
    public static double[] convertGdToTdt(String location) {
        String[] gdInfo = location.split(",");
        if(gdInfo.length != 2){
            throw new BusinessException("坐标转换失败!");
        }
        double gdLat = Double.valueOf(gdInfo[0]);
        double gdLon = Double.valueOf(gdInfo[1]);
        double[] wgs = transformFromGcjToWgs(gdLat, gdLon);
        return wgs;
    }

    private static double[] transformFromGcjToWgs(double gcjLat, double gcjLon) {
        double dLat = transformLat(gcjLon - 105.0, gcjLat - 35.0);
        double dLon = transformLon(gcjLon - 105.0, gcjLat - 35.0);
        double radLat = gcjLat / 180.0 * PI;
        double magic = Math.sin(radLat);
        magic = 1 - EE * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
        dLon = (dLon * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI);
        double wgsLat = gcjLat - dLat;
        double wgsLon = gcjLon - dLon;
        return new double[]{wgsLon, wgsLat};
    }

    private static double transformLat(double x, double y) {
        double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformLon(double x, double y) {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    public static void main(String[] args) {
        double gdLat = 39.90872021739812;
        double gdLon = 116.39749999999998;
//        double[] tdt = convertGdToTdt(gdLat, gdLon);
//        System.out.println("天地图经度: " + tdt[0] + ", 天地图纬度: " + tdt[1]);
    }


}
